/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */



package itm.conexion;

//~--- non-JDK imports --------------------------------------------------------

import itm.exception.ControlException;

import static itm.constants.DatabaseConstants.*;

//~--- JDK imports ------------------------------------------------------------

import java.sql.Connection;
import java.sql.SQLException;

import javax.naming.Context;
import javax.naming.InitialContext;
import javax.naming.NamingException;

import javax.sql.DataSource;

/**
 *
 * @author Administrador
 */
public class SQLServerConnection {
    Connection    dbConnection = null;
    DataSource    ds           = null;
    Context       envContext   = null;
    Context       initContext  = null;
    public String resEx;

    public Connection openConnection() throws ControlException {
        try {
            getDataSource();
            if (ds != null) {
                dbConnection = ds.getConnection();
                return dbConnection;
            } else {
                return null;
            }
        } catch (SQLException sqle) {
            sqle.printStackTrace();
            throw new ControlException(sqle.getMessage());
        }
    }

    public void closeConnection(Connection conexion)  {
        try {
            conexion.close();
        } catch (SQLException sqle) {
            sqle.getStackTrace();
        }
    }

    /**
      @return retorna el datasource
     */
       public void getDataSource() throws ControlException {
        try {
            initContext = new InitialContext();
            envContext  = (Context) initContext.lookup(CONTEXT_LOOKUP);
            ds          = (DataSource) envContext.lookup(SQLSERVER_DATASOURCE);
        } catch (NamingException e) {
            e.getStackTrace();
            throw new ControlException(e.getMessage());
        }
      }
    /**
      @return: Retorna la conexión, inicializando para dar comienzo a una transaccion
     */
    public Connection openTransaccion() throws ControlException {
        try {
            openConnection();
            dbConnection.setAutoCommit(false);
            return dbConnection;
        }catch(SQLException e) {
            e.printStackTrace();
            throw new ControlException("No se inicializo la transacción" + e.getMessage());
        }catch (ControlException sqle){
            sqle.printStackTrace();
            setResEx(sqle.toString());
            throw new ControlException("No se establecio la conexión a la base de datos" + sqle.getMessage());
        }
  }
	public void commit() throws ControlException{
		if(dbConnection == null){
			throw new ControlException("La conexión no se ha inicializado.  Se debe iniciar con begin().");
		}
		try {
			dbConnection.commit();
			dbConnection.setAutoCommit(true);
		    dbConnection.close();
		}
		catch (SQLException e) {
		    throw new ControlException(e.getMessage());
		}
	}

	public void rollback() throws ControlException{
	    if(dbConnection == null){
	        throw new ControlException("La conexión no se ha inicializado.  Se debe iniciar con begin().");
	    }
		try {
			dbConnection.rollback();
			dbConnection.setAutoCommit(true);
			dbConnection.close();
		}
		catch (SQLException e) {
		    throw new ControlException(e.getMessage());
		}
	}

    public String getResEx() {
        return resEx;
    }

    public void setResEx(String resEx) {
        this.resEx = resEx;
    }
}
